package com.yyh.io2;

import java.io.*;
import java.util.Arrays;

/*2.实现字节数组和任何基本类型和引用类型执行的相互转换
提示：使用ByteArrayInutStream和ByteArrayOutputStream。*/
public class Test22 {
    public static void main(String[] args) throws IOException {
        // 示例数据
        int number = 123;
        double price = 99.99;
        boolean flag = true;
        String text = "湖北软帝";

        // 基本类型和引用类型 → 字节数组
        byte[] byteArray = toByteArray(number, price, flag, text);
        System.out.println("转换后的字节数组: " + Arrays.toString(byteArray));

        // 字节数组 → 基本类型和引用类型
        fromByteArray(byteArray);
    }

    // 将各种类型转换为字节数组
    public static byte[] toByteArray(int num, double price, boolean flag, String text) throws IOException, IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             DataOutputStream dos = new DataOutputStream(baos)) {

            // 写入各种基本类型
            dos.writeInt(num);        // int → 字节
            dos.writeDouble(price);   // double → 字节
            dos.writeBoolean(flag);   // boolean → 字节
            dos.writeUTF(text);       // String → 字节（UTF-8编码）

            return baos.toByteArray();
        }
    }

    // 从字节数组解析回各种类型
    public static void fromByteArray(byte[] data) throws IOException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
             DataInputStream dis = new DataInputStream(bais)) {

            // 按写入顺序读取（顺序必须一致！）
            int restoredInt = dis.readInt();
            double restoredDouble = dis.readDouble();
            boolean restoredBoolean = dis.readBoolean();
            String restoredString = dis.readUTF();

            System.out.println("还原的int: " + restoredInt);
            System.out.println("还原的double: " + restoredDouble);
            System.out.println("还原的boolean: " + restoredBoolean);
            System.out.println("还原的String: " + restoredString);
        }
    }
}
